/**
 * Copyright 2013 yangming.liu<liuyangming@gmail.com>.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, see <http://www.gnu.org/licenses/>.
 */
package org.bytesoft.openjta.supports.internal;

import java.io.Serializable;

import javax.transaction.SystemException;

import org.bytesoft.openjta.TransactionContext;
import org.bytesoft.openjta.TransactionImpl;
import org.bytesoft.openjta.TransactionManagerImpl;
import org.bytesoft.openjta.internal.KeyInstance;
import org.bytesoft.openjta.resource.Terminator;
import org.bytesoft.openjta.supports.TerminatorMarshaller;
import org.bytesoft.openjta.supports.crm.RmiInterceptor;
import org.bytesoft.openjta.supports.crm.RmiRequest;
import org.bytesoft.openjta.supports.crm.RmiResponse;
import org.bytesoft.openjta.xa.XidImpl;

public class RmiInterceptorImpl implements RmiInterceptor {

	private TransactionManagerImpl transactionManager;
	private TerminatorMarshaller<Serializable> terminatorMarshaller;

	@Override
	public void beforeSendRequest(RmiRequest request) throws IllegalStateException {
		TransactionImpl transaction = this.getCurrentTransaction();
		KeyInstance token = this.transactionManager.getKeyInstance();
		if (transaction != null) {
			TransactionContext nativeContext = transaction.getTransactionContext();
			TransactionContext transactionContext = nativeContext.clone();
			XidImpl globalXid = transaction.getGlobalXid();
			transactionContext.setXid(globalXid);
			transactionContext.setPropagationToken(token);

			request.setTransactionContext(transactionContext);
		}
	}

	@Override
	public void afterRecvRequest(RmiRequest request) throws IllegalStateException {
		TransactionContext propagateContext = (TransactionContext) request.getTransactionContext();
		if (propagateContext != null) {
			TransactionContext transactionContext = propagateContext.clone();
			try {
				this.transactionManager.begin(transactionContext);
			} catch (SystemException ex) {
				IllegalStateException exception = new IllegalStateException();
				exception.initCause(ex);
				throw exception;
			}
		}
	}

	@Override
	public void beforeSendResponse(RmiResponse response) throws IllegalStateException {
		TransactionImpl transaction = this.getCurrentTransaction();
		if (transaction != null) {
			TransactionContext transactionContext = transaction.getTransactionContext();
			response.setTransactionContext(transactionContext);
		}
	}

	@Override
	public void afterRecvResponse(RmiResponse response) throws IllegalStateException {
		TransactionContext propagateContext = (TransactionContext) response.getTransactionContext();
		if (propagateContext != null) {
			KeyInstance nativeToken = this.transactionManager.getKeyInstance();
			KeyInstance remoteToken = propagateContext.getPropagationToken();

			if (nativeToken.equals(remoteToken)) {
				TransactionImpl transaction = this.getCurrentTransaction();
				TransactionContext nativeContext = transaction.getTransactionContext();

				boolean remoteContainsLocalResource = propagateContext.containsNonXAResource();

				Terminator terminator = this.terminatorMarshaller.getTerminator(response);
				transaction.registerTerminator(terminator, remoteContainsLocalResource);

				if (remoteContainsLocalResource) {
					nativeContext.setContainsNonXAResource(true);
				}

				if (propagateContext.isRollbackOnly()) {
					nativeContext.setRollbackOnly(true);
				}
			}
		}
	}

	private TransactionImpl getCurrentTransaction() throws IllegalStateException {
		if (this.transactionManager == null) {
			return null;
		}

		try {
			return this.transactionManager.getTransaction();
		} catch (SystemException ex) {
			IllegalStateException exception = new IllegalStateException();
			exception.initCause(ex);
			throw exception;
		}
	}

	public void setTerminatorMarshaller(TerminatorMarshaller<Serializable> terminatorMarshaller) {
		this.terminatorMarshaller = terminatorMarshaller;
	}

	public void setTransactionManager(TransactionManagerImpl transactionManager) {
		this.transactionManager = transactionManager;
	}

}
